package com.ly.service.impl;

import com.ly.dao.FileMapper;
import com.ly.dao.NewsMapper;
import com.ly.pojo.dto.FileDTO;
import com.ly.pojo.dto.NewsDTO;
import com.ly.pojo.query.NewsQuery;
import com.ly.service.HomeService;
import java.lang.Boolean;
import java.lang.Override;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ly.exception.BusinessException;
import java.util.Map;
import java.io.File;
import com.ly.pojo.domain.FileDO;
import com.ly.constant.ResultCodeConstant;
import com.ly.pojo.domain.NewsDO;

/**
 * 首页管理模块的实现
 *
 * @author Administrator
 * @date 2025-03-07 10:51:13
 */
@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private FileMapper fileMapper;

    @Override
    public Boolean addNews(NewsDTO newsDTO) {
        NewsDO existingNews = newsMapper.selectByTitle(newsDTO.getTitle());
        if (existingNews != null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        NewsDO newsDO = new NewsDO();
        newsDO.setTitle(newsDTO.getTitle());
        newsDO.setContent(newsDTO.getContent());
        newsDO.setImageUrl(newsDTO.getImageUrl());
        int result = newsMapper.insert(newsDO);
        return result > 0;
    }

    @Override
    public Boolean updateNews(NewsDTO newsDTO) {
        NewsDO existingNews = newsMapper.selectById(newsDTO.getNewsId());
        if (existingNews == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        existingNews.setTitle(newsDTO.getTitle());
        existingNews.setContent(newsDTO.getContent());
        existingNews.setImageUrl(newsDTO.getImageUrl());
        int result = newsMapper.updateById(existingNews);
        return result > 0;
    }

    @Override
    public Boolean deleteNews(NewsQuery newsQuery) {
        NewsDO existingNews = newsMapper.selectById(newsQuery.getNewsId());
        if (existingNews == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        int result = newsMapper.deleteById(newsQuery.getNewsId());
        return result > 0;
    }

    @Override
    public Boolean uploadFile1(FileDTO fileDTO) {
        FileDO existingFile = fileMapper.selectByFileName(fileDTO.getFileName());
        if (existingFile != null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        FileDO fileDO = new FileDO();
        fileDO.setFileName(fileDTO.getFileName());
        fileDO.setFilePath(fileDTO.getFilePath());
        fileDO.setFileType(fileDTO.getFileType());
        int result = fileMapper.insert(fileDO);
        return result > 0;
    }
}
